package top.xierongsheng.user.validate.impl;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import top.xierongsheng.user.dto.ResourceDto;
import top.xierongsheng.user.model.SysArea;
import top.xierongsheng.user.service.IAreaService;
import top.xierongsheng.user.validate.ValidLevel;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class LevelValidator implements ConstraintValidator<ValidLevel, Integer> {
    @Autowired
    private IAreaService areaService;

    @Override
    public void initialize(ValidLevel constraintAnnotation) {
        Class<ResourceDto> cls1 = ResourceDto.class;
        Field[] fields = cls1.getDeclaredFields();
        if (fields == null) return;
        StringBuilder sb = new StringBuilder();
        sb.append("获得类的所有属性信息：\n\n");
        for (Field field : fields) {
            sb.append(Modifier.toString(field.getModifiers())).append(" ");
            sb.append(field.getType().getSimpleName()).append(" ");
            sb.append(field.getName()).append(";");
            sb.append("\n\n");
        }

        try {
            sb.append("属性i的默认值：i = ");
            Field f = cls1.getDeclaredField("i");
            sb.append(f.getInt("i")).append("\n\n");
            f.set("i", 100);
            sb.append("属性i修改后的值：i = ");
            sb.append(f.getInt("i")).append("\n\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isValid(Integer param, ConstraintValidatorContext constraintValidatorContext) {
        SysArea sysArea = areaService.getByAreaId(param);
        if (sysArea == null) {
            return false;
        }
        return true;
    }
}
